package com.zmx.patientend.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zmx.patientend.R;
import com.zmx.patientend.pojo.ChatPojo;

import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


/**
 *
 * 开发者：胖胖祥
 * 时间：2016/11/3 21:50
 * 功能模块：聊天界面的适配器
 *
 */
public class ChatAdapter extends BaseAdapter {

    private Context context;
    private List<ChatPojo> lists;
    private LayoutInflater inflater;

    public ChatAdapter(Context context, List<ChatPojo> lists){

        this.context = context;
        this.lists = lists;
        inflater = LayoutInflater.from(context);

    }

    @Override
    public int getCount() {
        return lists.size();
    }

    @Override
    public Object getItem(int position) {
        return lists.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    // 判断使用那个布局
    @Override
    public int getItemViewType(int position) {

        ChatPojo cp = lists.get(position);

        if (cp.getRole() == 2) {

            return 0;

        }

        return 1;
    }

    // 返回多少个布局
    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent) {

        ChatPojo chat = lists.get(position);
        ViewHolder holder = null;

        if (v == null) {

            holder = new ViewHolder();

            if (getItemViewType(position) == 0) {

                v = inflater.inflate(R.layout.chat_user, null);
                holder.mMsg = v.findViewById(R.id.u_msg);
                holder.head = v.findViewById(R.id.u_head);
                holder.name = v.findViewById(R.id.u_name);
                holder.time = v.findViewById(R.id.u_time);
                v.setTag(holder);

            } else {

                v = inflater.inflate(R.layout.chat_login, null);
                holder.mMsg =  v.findViewById(R.id.l_msg);
                holder.head = v.findViewById(R.id.l_head);
                holder.name = v.findViewById(R.id.l_name);
                holder.time = v.findViewById(R.id.l_time);
                v.setTag(holder);

            }

        } else {

            holder = (ViewHolder) v.getTag();
        }

        // 设置数据
        holder.mMsg.setText(chat.getContent());
        Glide.with(context).load(chat.getAvatar()).into(holder.head);
        holder.name.setText(chat.getName());
        holder.time.setText("回复时间："+chat.getReplytime());
        //处理刷新数据后闪屏问题
        holder.head.setScaleType(ImageView.ScaleType.CENTER_CROP);

        return v;
    }

    private final class ViewHolder {

        TextView mMsg,name,time;
        CircleImageView head;

    }

}
